using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace FolderSync
{
    public enum IconSize
    {
        Large,
        Small
    }

	public class FileIcon
	{
		[StructLayout(LayoutKind.Sequential)]
		struct SHFILEINFO
		{
			public IntPtr hIcon;
			public int iIcon;
			public int dwAttributes;
			public string szDisplayName;
			public string szTypeName;
		}

		private const uint SHGFI_SYSICONINDEX = 0x4000;
		private const uint SHGFI_ICON = 0x100;
		private const uint SHGFI_LARGEICON = 0x0;
		private const uint SHGFI_SMALLICON = 0x1;
		private const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;
		private const uint SHGFI_OPENICON = 0x000000002;
		private const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;

		[DllImport("Shell32.dll")]
		private static extern int SHGetFileInfo(string path, uint fileAttributes, out SHFILEINFO psfi, uint fileInfo, uint flags);

		public static Icon GetIcon(string path, IconSize iconSize)
		{
			SHFILEINFO info = new SHFILEINFO();
			uint size = (iconSize == IconSize.Large) ? SHGFI_LARGEICON : SHGFI_SMALLICON;
			uint flags = SHGFI_SYSICONINDEX | size | SHGFI_ICON;
			int hTcdf = SHGetFileInfo(path, 0, out info, (uint)Marshal.SizeOf(typeof(SHFILEINFO)), flags);
			IntPtr handleIcon = info.hIcon;
			Icon ico = Icon.FromHandle(handleIcon);
			return ico;
		}

		public static Icon GetFolderIcon(IconSize iconSize)
		{
			uint flags = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES;
			//flags += SHGFI_OPENICON;
			flags += (iconSize == IconSize.Large) ? SHGFI_LARGEICON : SHGFI_SMALLICON;
			SHFILEINFO shfi = new SHFILEINFO();
			int hTcdf = SHGetFileInfo(null, FILE_ATTRIBUTE_DIRECTORY, out shfi, (uint)Marshal.SizeOf(shfi), flags);
			Icon ico = Icon.FromHandle(shfi.hIcon);
			return ico;
		}
	}
}
